import { AppTypeEnum } from '../enums'
/**
 * @description url取值
 * @param {*} key
 * @param {*} href
 */
export function getQueryString(key: string, href = '') {
  let search = href || window.location.search
  const { location: { hash } } = window
  if (!search && hash) {
    search = hash.substring(1)
  }
  const reg = new RegExp(`(^|\\?|&)${key}=([^&]*)(&|$)`)
  const res = search.match(reg)
  return res ? res[2] : ''
}

const WindowResources: Array<string> = []
/**
 * @description 动态引入资源，用于单易引入不用编译的js/css 减少编译负担
 * @param {string} src 资源路径
 * @param {function} callback 回调函数，只适用于js
 * @param {boolean} noLoad 跳过加载直接执行回调
 */
export const loadResources = (src: string, callback?: Function, noLoad?: boolean) => {
  if (WindowResources.includes(src) || noLoad) {
    return callback && callback()
  }
  if (!src) {
    return (console.log(new Error('please set the src of script/css')))
  }
  // load javascript
  if (/\.js(\?v=.*){0,1}$/.test(src)) {
    const script = document.createElement('script')
    script.src = src
    script.type = 'text/javascript'
    const headEle = document.getElementsByTagName('head')[0]
    // IE
    const IeScript = script as any
    if (IeScript.readyState) {
      IeScript.onreadystatechange = () => {
        if (IeScript.readyState === 'loaded' || IeScript.readyState === 'complete') {
          callback && callback()
          IeScript.onreadystatechange = null
        }
      }
    // webkit opera
    } else {
      script.onload = () => {
        callback && callback()
      }
    }
    headEle.appendChild(script)
    WindowResources.push(src)
    // load stylesheet
  } else if (/\.css$/.test(src)) {
    const styleSheet = document.createElement('link')
    styleSheet.href = src
    styleSheet.rel = 'stylesheet'
    const headEle = document.getElementsByTagName('head')[0]
    headEle.appendChild(styleSheet)
    WindowResources.push(src)
  }
}

/**
 * @description cookies 操作
 */
export const Cookies = {
  /**
   * @param {Object} data cookie key,value
   * @param {String} path cookie path
   * @param {Date} expiresDate 过期时间/默认会话过期 Todo
   * @description
   */
  set(data: Record<any, any>, path = '/', expiresDate: Date) {
    const expires = expiresDate instanceof Date ? expiresDate.toUTCString() : expiresDate

    Object.keys(data).forEach(key => {
      document.cookie = `${key}=${data[key]};path=${path};expires=${expires}`
    })
  },

  /**
   * @description 获取指定cookie
   * @param {*} Key
   */
  get(key: string) {
    const arrStr = document.cookie.split('; ')
    for (let i = 0; i < arrStr.length; i++) {
      const temp = arrStr[i].split('=')
      if (temp[0] === key) {
        return decodeURI(temp[1])
      }
    }
  },

  /**
   * @description 删除cookie
   * @param {} key
   */
  remove(key: string ) {
    const now = new Date()
    const expires = new Date(now.getTime() - 1000).toUTCString()
    document.cookie = `${key}=;expires=${expires}`
  }

}

/**
 * @description 判断是否在微信浏览器内
 */
export function isWeiXin() {
  const ua = window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i)
  return ua && ua[0] === 'micromessenger'
}


/**
 * @description 延迟执行函数
 * @param { number } duration 持续时间, 默认持续时间为 1s
 */
export function delayExecution(duration = 1000) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true)
    }, duration)
  })
}

/**
 * @description 获取倒计时
 * @param { number } timeStamp 时间戳
 * @param { boolean } isMillisecond 是否毫秒时间戳，默认是毫秒
 * @param { boolean } isAddZero 不足十位是否补领
 */
export function getCountdownText(timeStamp: number, isMillisecond = true, isAddZero = false) {
  // 毫秒时间戳转化为秒时间戳
  if(isMillisecond) timeStamp = Math.floor(timeStamp / 1000)
  const days = Math.floor(timeStamp / (60 * 60 * 24))
  const hour = Math.floor((timeStamp % (60 * 60 * 24)) / (60 * 60))
  const min = Math.floor((timeStamp % (60 * 60)) / 60)
  const scn = Math.floor((timeStamp % 60))
  const addZeroFn = (count: number) => {
    return isAddZero ? (count < 10 ? `0${count}` : count) : count
  }
  let sm = ''
  if (days > 0) sm += `${addZeroFn(days)}天`
  if (days > 0 || hour > 0) sm += `${addZeroFn(hour)}小时`
  if (days > 0 || min > 0) sm += `${addZeroFn(min)}分`
  if (days > 0 || scn > 0) sm += `${addZeroFn(scn)}秒`
  return sm
}

/**
 * 小数点保留位数处理
 * @param { number } number - 小数
 * @param { number } count - 保留位数
 * @export number
 */
export const toFixed = (number: number, count: number) => {
  return Math.round(number * Math.pow(10, count)) / Math.pow(10, count)
}

/**
 * @description 千分位处理
 * @param { number } num 需要格式化的数据，支持小数
*/
export const formatThousands = (num: number) => {
//   const reg =/\d{1,3}(?=(\d{3})+$)/g
//   return (num + '').replace(reg, '$&,')
// }

  let tem: string = num + ''
  if (!tem.includes('.')) {
    tem += '.'
  }
  return tem.replace(/(\d)(?=(\d{3})+\.)/g, (a, b) => {
    return b + ','
  }).replace(/\.$/, '')
}


/**
 * @module utils/object
 * @author caoshitong@moretickets.com
 * @description JS对象操作
 */


/**
 * @description 根据传入对象的路径取值
 * @param {object} 传入对象 eg. {a:{b:{c:{d:111}}}}
 * @param {string} 属性path  eg. a.b.c.d
 * @returns { * } 跟据路径获取到的 value
 */
export const objGet = (object: any, propertyPath: string) => {
  let srcObj = object
  const paths = propertyPath.split('.')
  for (let index = 0; index < paths.length; index += 1) {
    const key = paths[index]
    if (srcObj[key]) {
      srcObj = srcObj[key]
    } else {
      return undefined
    }
  }
  return srcObj
}

/**
 * @description 对象深拷贝
 * @param {object} object - 被拷贝的对象
 * @return {object} 新对象
 */
export const deepClone = (object: any) => {
  const obj = object
  let targetObj = {}
  // 递归出口
  // if (typeof obj !== 'object' || obj == null) {
  if (typeof obj !== 'object' || !obj) {
    return obj
  }

  if (obj instanceof Array) {
    targetObj = []
  }

  Object.keys(obj).forEach(key => {
    targetObj[key] = deepClone(obj[key])
  })

  return targetObj
}

/**
 * @description 返回版本比较结果
 * @param {*} v1
 * @param {*} v2
 */
export function diffVersion(v1: string, v2: string) {
  let v1Array = v1.split('.')
  let v2Array = v2.split('.')
  //
  const maxLength = Math.max(v1Array.length, v2Array.length)
  // 补零
  v1Array = v1Array.concat(new Array(maxLength - v1Array.length).fill(0)).map(item => item)
  v2Array = v2Array.concat(new Array(maxLength - v2Array.length).fill(0)).map(item => item)

  let i = 0
  while (i < maxLength) {
    if (Number(v1Array[i]) < Number(v2Array[i])) return '<'
    if (Number(v1Array[i]) > Number(v2Array[i])) return '>'
    i += 1
  }
  return '='
}

/**
 * @description 获取当前APP版本
 */
export function getAppVersion() {
  // "Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 HeyHeyTalk/2.13.6;OS/iOS HeyHeyTalk/2.13.6"
  /HeyHeyTalk\/(\d*\.\d*\.\d*);/.test(window.navigator.userAgent)
  return RegExp.$1
}

/**
 * @description 获取当前APP类型
 */
export function getAppType() {
  const ua = window.navigator.userAgent
  if(/HeyHeyTalk--TaiKongSa/.test(ua)){
    return AppTypeEnum.HEYTAIKONGSA
  }else{
    return AppTypeEnum.HEYHEY
  }
}
